package cn.fsd.service.impl;

import cn.fsd.mapper.StationMapper;
import cn.fsd.domain.*;
import cn.fsd.mapper.*;
import cn.fsd.query.BaseQuery;
import cn.fsd.service.BaiduService;
import cn.fsd.service.TaskService;
import cn.fsd.vo.LocationPoint;
import cn.fsd.vo.PageBean;
import cn.fsd.vo.PointBean;
import cn.fsd.vo.TaskBean;
import cn.hutool.core.lang.UUID;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class TaskServiceImpl implements TaskService {

    @Autowired
    TaskMapper taskMapper;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    Customer_addressMapper customer_addressMapper;

    @Autowired
    StationMapper stationMapper;

    @Autowired
    CommodityMapper commodityMapper;

    @Autowired
    CustomerMapper customerMapper;

    @Autowired
    TransferMapper transferMapper;

    @Autowired
    StoreroomMapper storeroomMapper;

    @Autowired
    Transfer_pathMapper transfer_pathMapper;

    @Autowired
    BaiduService baiduService;

    @Override
    public String add(String order_id) {
        //根据前端获取的order_id在order表中确定订单
        Order order = orderMapper.selectByPrimaryKey(order_id);
        //根据所查询到订单的customer_id和address_choice在customer_address表中查询对应的数据
        Customer_address customer_address = customer_addressMapper.selectByPrimaryKey(order.getCustomer_id(), order.getAddress_choice());
        //获取到收货人地址
        String delivery_address = customer_address.getReceiver_address();
        //通过百度地图api查询地址对应的经纬度数据
        double[] deliveryLocationPoint = baiduService.getGeoByAddress(delivery_address);
        if(deliveryLocationPoint==null){
            return "fail";
        }
        //遍历分站，通过百度地图api计算收货人地址到每个分站的距离和时间来选择分站（策略：优先选时间最短，时间相等选距离最短）
        List<Station> stationList = stationMapper.selectAll();
        int index = -1;//记录符合条件的分站下标
        double minDistance = Integer.MAX_VALUE;
        double minTime = Integer.MAX_VALUE;
        for (int i = 0; i < stationList.size(); i++) {
            //获取该分站地址
            String station_place = stationList.get(i).getStation_place();
            //通过百度地图api查询地址对应的经纬度数据
            double[] stationLocationPoint = baiduService.getGeoByAddress(station_place);
            if(stationLocationPoint==null){//分站地址无法逆编码时直接跳过
                continue;
            }
            //通过百度地图api计算收货人地址到每个分站的距离和时间
            double[] distenceAndTime = baiduService.getDistenceAndTime(String.valueOf(deliveryLocationPoint[1]) + "," + String.valueOf(deliveryLocationPoint[0]), String.valueOf(stationLocationPoint[1]) + "," + String.valueOf(stationLocationPoint[0]));
            //**********这是一个测试**********
//            System.out.println("distance:"+distenceAndTime[0]+" time:"+distenceAndTime[1]);
            if(distenceAndTime[1]<minTime){
                index = i;
                minDistance = distenceAndTime[0];
                minTime = distenceAndTime[1];
            }else if(distenceAndTime[1]==minTime&&distenceAndTime[0]<minDistance){
                index = i;
                minDistance = distenceAndTime[0];
                minTime = distenceAndTime[1];
            }
        }
        Station station = stationList.get(index);
        Task task = new Task();
        task.setTask_id(UUID.randomUUID().toString());
        task.setOrder_id(order_id);
        task.setStation_id(station.getStation_id());
        task.setTask_genDate(new Date());
        //********以下字段需要根据需求设置*********
        task.setTask_finDate(new Date());//要求完成日期
        task.setTask_deliveryDate(new Date());//送货日期
        task.setTask_type("送货");//任务类型
        task.setTask_status("完成");//任务类型
        task.setCount_inTask(1);//商品数量
        task.setCourier_id("1");//配送员
        int count = taskMapper.insert(task);
        if(count==1)
            return "success";
        return "fail";
    }

    @Override
    public PageBean<Task> findByPage(BaseQuery query) {
        //构建结果对象
        PageBean<Task> pageBean = new PageBean<>();

        //开启分页
        PageHelper.startPage(query.getPageNow(),query.getPageSize());

        //分页查询得到当页的集合
        List<Task> taskList = taskMapper.findByPage(query);

        //创建一个分页的实体PageInfo
        PageInfo<Task> pageInfo = new PageInfo<>(taskList);

        pageInfo.setList(pageInfo.getList().stream().map(task -> {
            TaskBean bean = new TaskBean(task);
            Order order = orderMapper.selectByPrimaryKey(task.getOrder_id());
            bean.setCustomer_name(customerMapper.selectByPrimaryKey(order.getCustomer_id()).getCustomer_name());
            bean.setReceiver_address(customer_addressMapper
                    .selectByPrimaryKey(order.getCustomer_id(),order.getAddress_choice()).getReceiver_address());
            bean.setCommodity_name(commodityMapper.selectByPrimaryKey(order.getCommodity_id()).getCommodity_name());
            return bean;
        }).collect(Collectors.toList()));

        pageBean.setTotalRows(pageInfo.getTotal());
        pageBean.setTotalPages(pageInfo.getPages());
        pageBean.setRowData(pageInfo.getList());

        return pageBean;
    }

    @Override
    public List<PointBean> showPoint(String task_id){
        List<PointBean> pointList = new ArrayList<>();
        Task task = taskMapper.selectByPrimaryKey(task_id);
        //查询收货人信息
        PointBean receiver = new PointBean();
        Order order = orderMapper.selectByPrimaryKey(task.getOrder_id());
        String receiver_address = customer_addressMapper.selectByPrimaryKey(order.getCustomer_id(), order.getAddress_choice()).getReceiver_address();
        receiver.setFlag("receiver");
        receiver.setAddress(receiver_address);
        //通过百度地图api查询地址对应的经纬度数据
        double[] receiverLocationPoint = baiduService.getGeoByAddress(receiver_address);
        receiver.setLat(String.valueOf(receiverLocationPoint[1]));
        receiver.setLng(String.valueOf(receiverLocationPoint[0]));
        pointList.add(receiver);
        //查询所选分站信息
        PointBean point_station = new PointBean();
        Station station = stationMapper.selectByPrimaryKey(task.getStation_id());
        point_station.setFlag("station_choice");
        point_station.setId(station.getStation_id());
        point_station.setAddress(station.getStation_place());
        point_station.setName(station.getStation_name());
        point_station.setPhone(station.getStation_phone());
        //通过百度地图api查询地址对应的经纬度数据
        double[] stationLocationPoint = baiduService.getGeoByAddress(station.getStation_place());
        point_station.setLat(String.valueOf(stationLocationPoint[1]));
        point_station.setLng(String.valueOf(stationLocationPoint[0]));
        pointList.add(point_station);
        return pointList;
    }

    @Override
    public List<PointBean> showAllPoint(String task_id) {
        List<PointBean> pointList = new ArrayList<>();
        Task task = taskMapper.selectByPrimaryKey(task_id);
        //查询收货人信息
        PointBean receiver = new PointBean();
        Order order = orderMapper.selectByPrimaryKey(task.getOrder_id());
        String receiver_address = customer_addressMapper
                .selectByPrimaryKey(order.getCustomer_id(), order.getAddress_choice())
                .getReceiver_address();
        receiver.setFlag("receiver");
        receiver.setAddress(receiver_address);
        //通过百度地图api查询地址对应的经纬度数据
        double[] receiverLocationPoint = baiduService.getGeoByAddress(receiver_address);
        receiver.setLat(String.valueOf(receiverLocationPoint[1]));
        receiver.setLng(String.valueOf(receiverLocationPoint[0]));
        pointList.add(receiver);
        //查询所有分站信息
        List<Station> stations = stationMapper.selectAll();
        String station_id_choice = task.getStation_id();//所选分站id
        //遍历全部分站
        for (int i = 0; i < stations.size(); i++) {
            Station station = stations.get(i);
            String station_address = station.getStation_place();
            //查询分站信息
            PointBean cur_station = new PointBean();
            //遍历到的当前分站正是所选分站 
            if(station.getStation_id().equals(station_id_choice)){
                cur_station.setFlag("station_choice");
            }else{
                cur_station.setFlag("station_other");
            }
            cur_station.setId(station.getStation_id());
            cur_station.setAddress(station_address);
            cur_station.setName(station.getStation_name());
            cur_station.setPhone(station.getStation_phone());
            //通过百度地图api查询地址对应的经纬度数据
            double[] stationLocationPoint = baiduService.getGeoByAddress(station_address);
            cur_station.setLat(String.valueOf(stationLocationPoint[1]));
            cur_station.setLng(String.valueOf(stationLocationPoint[0]));
            pointList.add(cur_station);
        }
        return pointList;
    }

//    @Override
//    public String update(String task_id, String station_id) {
//        Task task = taskMapper.selectByPrimaryKey(task_id);
//        task.setStation_id(station_id);
//        int count = taskMapper.updateByPrimaryKey(task);
//        if(count==1)
//            return "success";
//        return "fail";
//    }

    @Override
    public String update(String task_id, String station_id) {
        //修改task表中的所选分站
        Task task = taskMapper.selectByPrimaryKey(task_id);
        task.setStation_id(station_id);
        taskMapper.updateByPrimaryKey(task);
        //退货不存在调度单
        if(!"退货".equals(orderMapper.selectByPrimaryKey(task.getOrder_id()).getOrder_type())){
            //修改transfer表中的所选分站
            Transfer transfer = transferMapper.selectByOrderId(task.getOrder_id());
            transfer.setStation_id(station_id);
            transferMapper.updateByPrimaryKey(transfer);
            //根据新的分站重新路线规划生成新路径并保存，在transfer_path中根据transfer_id先删除，再添加
            double[] storeroomLocationPoint = baiduService.getGeoByAddress(storeroomMapper.selectByPrimaryKey(transfer.getStoreroom_id()).getStoreroom_place());
            double[] stationLocationPoint = baiduService.getGeoByAddress(stationMapper.selectByPrimaryKey(station_id).getStation_place());
            String waypoints = null;
            List<List<LocationPoint>> routes = baiduService.getRoute(String.valueOf(storeroomLocationPoint[1]) + "," + String.valueOf(storeroomLocationPoint[0]), String.valueOf(stationLocationPoint[1]) + "," + String.valueOf(stationLocationPoint[0]), waypoints);

            int count = transfer_pathMapper.countById(transfer.getTransfer_id());
            for (int i = 0; i < count; i++) {
                transfer_pathMapper.deleteByPrimaryKey(transfer.getTransfer_id(),i);
            }

            for (int i = 0; i < routes.size(); i++) {
                List<LocationPoint> route = routes.get(i);
                Transfer_path transfer_path = new Transfer_path();
                transfer_path.setTransfer_id(transfer.getTransfer_id());
                transfer_path.setPath_num(i);
                transfer_path.setPath_info(route.toString());
                transfer_pathMapper.insert(transfer_path);
            }
        }
        return "success";
    }

    @Override
    public String sure(String task_id) {
        //修改任务状态
        Task task = taskMapper.selectByPrimaryKey(task_id);
        if("调度中".equals(task.getTask_status())){
            task.setTask_status("已调度");
            int count = taskMapper.updateByPrimaryKey(task);
            if(count!=1) return "fail";
        }
        //修改订单状态
        Order order = orderMapper.selectByPrimaryKey(task.getOrder_id());
        if("退货".equals(order.getOrder_type())&&"调度中".equals(order.getOrder_status())){
            order.setOrder_status("已调度");
            int count = orderMapper.updateByPrimaryKey(order);
            if(count!=1) return "fail";
        }
        return "success";
    }

    @Override
    public String getTaskIdByOrderId(String order_id) {
        return taskMapper.selectByOrderId(order_id).getTask_id();
    }
}
